package com.itheima.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.common.BaseContext;
import com.itheima.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 拦截所有请求，检查客户是否已完成登录
 */
@Slf4j
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    //路径匹配器，支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestURI = request.getRequestURI();
        log.info("拦截到请求：{}",requestURI);
        //设置不被拦截的路径
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg",
                "/user/login",
//                接口文档静态资源放行
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"
        };
        //调用方法判断本次请求是否需要处理
        boolean check = check(requestURI, urls);
        if (check) {
            log.info("本次请求{}不需要处理",requestURI);
            filterChain.doFilter(request, response);
            return;
        }
        //判断后端用户是否为登录状态
        if (request.getSession().getAttribute("employee") != null) {
            Long employee = (Long) request.getSession().getAttribute("employee");
            log.info("用户已登录，id为:{}",employee);
            BaseContext.setCurrentId(employee);
            filterChain.doFilter(request, response);
            return;
        }
        //判断用户端是否为登录状态
        if(request.getSession().getAttribute("user")!=null){
            log.info("用户已登录，用户id为:{}",request.getSession().getAttribute("user"));
            Long userId = (Long) request.getSession().getAttribute("user");
            BaseContext.setCurrentId(userId);
            log.info("当前登录用户id为:{}已保存至线程空间",BaseContext.getCurrentId());
            filterChain.doFilter(request,response);
            return;
        }
        log.info("用户未登录");
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }

    /**
     * 路径匹配检查本次请求是否需要放行
     * @param requestURI
     * @param urls
     * @return
     */
    private boolean check(String requestURI, String[] urls) {

        for (String s : urls) {
            boolean match = PATH_MATCHER.match(s, requestURI);
            if (match) {
                return true;
            }
        }
        return false;
    }
}
